package com.hfzy.ihk.web.oauth.server.conf;


import com.hfzy.ihk.web.oauth.server.customExceptionTranslator.CustomWebResponseExceptionTranslator;
import com.hfzy.ihk.web.oauth.server.handler.MyUserAuthenticationConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * Created by chenzesen on 2019/1/2.
 * <p>
 * 授权中心权限配置类，请谨慎修改
 */
@Configuration
@EnableAuthorizationServer
public class OAuthServerConfig extends AuthorizationServerConfigurerAdapter {


    /**
     * 自定义异常处理和异常返回
     */
    @Autowired(required = false)
    CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;


    @Autowired(required = false)
    private BCryptPasswordEncoder passwordEncoder;
//
////    @Resource("userDetailsServiceImpl")
////    UserDetailsService userDetailsService
//
    @Autowired(required = false)
    private AuthenticationManager authenticationManager;

    /**
     * 用于重写授权服务器返回用户给资源端或者服务器端
     */
    @Autowired(required = false)
    private MyUserAuthenticationConverter myUserAuthenticationConverter;

    /**
    * 注入redis 工厂
     */
    /*
    @Autowired
    private RedisConnectionFactory connectionFactory;
    */
    @Autowired(required = false)
    private DataSource dataSource;

    /**
     * 自定义实现将token 存储在redis 中，也可以存在数据中，有默认的表结构
     * @return
     */
    /*
    @Bean
    public RedisTokenStore tokenStore() {
        return new RedisTokenStore(connectionFactory);
    }
    */
    @Bean("jdbcTokenStore")
    public JdbcTokenStore getJdbcTokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean // 声明 ClientDetails实现
    public ClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }



    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
              //  .checkTokenAccess("isAuthenticated()")
//                .sslOnly()
                .allowFormAuthenticationForClients(); //允许客户端验证，用于开启客户端模式

    }

    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        //sso存储在内存中的授权码模式 和  //存储在redis 的授权码模式 和 jdbc 存储模式
        /**----------通过数据库配置客户端信息--------*/
         clients.withClientDetails(clientDetailsService());
        /**----------通过内存配置客户端信息--------*/
        //clients.jdbc(dataSource).w
       //clients.inMemory()
//                .withClient("ihksso") // clientId, 可以类比为用户名
//                .secret(passwordEncoder.encode("secret")) // secret， 可以类比为密码
//                .authorizedGrantTypes("authorization_code")    // 授权类型，这里选择授权码
//                .scopes("user_info") // 授权范围
//                .autoApprove(true) // 自动认证不然会多谈一个选择认证权限的页面
//                .redirectUris("http://10.10.37.142:8082/login","http://10.10.37.142:8083/login","http://10.10.37.142:8880/linkcall/login")  // 认证成功重定向URL 这里要包含作用域，用来控制单点登录的安全很重要
//                .accessTokenValiditySeconds(1000) // 超时时间，10000s
//
//                 //客户端模式可以用来客户端间api接口调用的验证 获取toke url auth/oauth/token?grant_type=client_credentials&client_id=client_ihk&client_secret=123456
//                .and().withClient("client_ihk")
//                .authorizedGrantTypes("client_credentials","refresh_token")
//                .scopes("all","read", "write")
////                .authorities("client_credentials")
//                .secret(passwordEncoder().encode("1"))
//                .accessTokenValiditySeconds(7200);


    }

    /**
     * 配置redis 或者jdbc存储token
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        DefaultAccessTokenConverter defaultAccessTokenConverter=new DefaultAccessTokenConverter();
        defaultAccessTokenConverter.setUserTokenConverter(myUserAuthenticationConverter); //用于重写授权服务器返回用户给资源端或者服务器端
        //端点支撑get请求
        endpoints
                .authenticationManager(authenticationManager)
        .tokenStore(getJdbcTokenStore())  //这里可以改成redis 存储不过不好管理，还是选择jdbc
//         .userDetailsService(userDetailsServiceImpl)
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        endpoints.tokenServices(defaultTokenServices()).accessTokenConverter(defaultAccessTokenConverter);
        //添加自定义异常处理
      //  endpoints.exceptionTranslator(customWebResponseExceptionTranslator);




    }



        /**
         * <p>注意，自定义TokenServices的时候，需要设置@Primary，否则报错，</p>
         * @return
         */
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(getJdbcTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetailsService());
        tokenServices.setAccessTokenValiditySeconds(60*60*12); // token有效期自定义设置，默认12小时
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//默认30天，这里修改

        return tokenServices;
    }




}
